from flask import jsonify, request

from myApp.model.build_model import BuildInfo
from flask import Blueprint

import mysql.connector

build_db = Blueprint('build', __name__)


@build_db.route('/build/<build_id>/<page>/<size>', methods=['GET'])
def get_build_by_id(build_id, page, size):
    page = max(1, int(page))
    size = max(1, int(size))
    offset = (page - 1) * size

    build = BuildInfo.get_build_by_id(build_id)
    if build is None:
        return jsonify({
            "message": "build not found"
        }), 404

    # 连接数据库
    connection = mysql.connector.connect(
        host='127.0.0.1',
        user='root',
        password='vsoft@123&',
        database='chatweb'
    )
    cursor = connection.cursor()

    # 获取总行数
    total_sql_str = f"SELECT COUNT(*) FROM ({build.sql_str}) AS count_table"
    cursor.execute(total_sql_str)
    total = cursor.fetchone()[0]

    # 执行分页查询
    paginated_sql_str = f"{build.sql_str} LIMIT {size} OFFSET {offset}"
    cursor.execute(paginated_sql_str)

    # 提取表头
    headers = [description[0] for description in cursor.description]
    # 数组字典，字段从1开始
    arr = []
    head_title = [index for index in range(len(headers))]

    for row in cursor.fetchall():
        arr.append(dict(zip(head_title, row)))

    # 关闭数据库连接
    cursor.close()
    connection.close()

    return jsonify(
        headers=headers,
        list=arr,
        total=total  # 返回总行数
    ), 200
